#include "Timer.h"

Timer::Timer(GLfloat x, GLfloat y)
{
	scrPosX = x;
	scrPosY = y;
	
	dTime = 0.0;
}

Timer::~Timer()
{
}

/* Change view to allow timer to be displayed in screen coordinates */
void Timer::setOrthographicProjection() 
{
	// switch to projection mode
	glMatrixMode(GL_PROJECTION);

	// save previous matrix which contains the 
	//settings for the perspective projection
	glPushMatrix();

	// reset matrix
	glLoadIdentity();

	// set a 2D orthographic projection, width = height = 40
	gluOrtho2D(0.0, 40.0, 0.0, 40.0);

	// mover the origin from the bottom left corner
	// to the upper left corner
	glTranslatef(0.0, 40.0, 0.0);

	glMatrixMode(GL_MODELVIEW);
}

/* Reset view to previous settings to render other objects correctly */
void Timer::resetPerspectiveProjection() 
{
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
}


// Origin is the top-left corner for time display
void Timer::displayTime()
{
	setText();

	setOrthographicProjection();
	glLoadIdentity();

	glPushMatrix();
		glColor3f(1.0f, 1.0f, 1.0f);
			
		glTranslatef(scrPosX, -scrPosY, 0.0);
		glScalef(0.015f, 0.02f, 0.02f);
		for (unsigned int i = 0; i < sTime.size(); i++)
		{
			glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, sTime[i]);
		}
	glPopMatrix();

	resetPerspectiveProjection();
}

void Timer::setText()
{
	time(&end);
	dTime = difftime(end, start);
	
	stringstream buf;
	
        // first char should be 0 if minutes are less than 10
	if (dTime/60.0 < 10.0)
		buf << "0";
	buf << (int)dTime/60;
	sTime = buf.str() + ":";   // minutes
	
	buf.str("");
	
        // first char should be 0 if seconds are less than 10
	if ((int)dTime%60 < 10)
		buf << "0";
	buf << (int)dTime%60;
	sTime += buf.str();   // seconds
}

void Timer::startTimer()
{
	time(&start);
}
